
package com.admin.controller;

import java.io.File;
import java.io.IOException;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.admin.dao.AdminDao;
import com.admin.domain.ItemCommand;
import com.admin.validator.ItemValidator;
import com.util.FileUtil;

@Controller
public class AdminItemInsertController {

	@Autowired
	private AdminDao adminDao;
	
	@RequestMapping(value="/shop/itemInsert.do", method=RequestMethod.GET)
	public String form(){
		return "itemInsert";
	}
	
	@ModelAttribute
	public ItemCommand formBacking(){
		return new ItemCommand();
	}

	@RequestMapping(value="/shop/itemInsert.do", method=RequestMethod.POST)
	public String submit(@Valid ItemCommand itemCommand,BindingResult result){
		
		if(result.hasErrors()){
			return form();
		}
		
		try{
			String  newName = "";
			
			if(!itemCommand.getUpload().isEmpty()){
				newName = FileUtil.rename(itemCommand.getUpload().getOriginalFilename());
				itemCommand.setI_image1(newName);
			}
			
			adminDao.insertItem(itemCommand);
			
			if(!itemCommand.getUpload().isEmpty()){
				File file = new File(FileUtil.UPLOAD_PATH + "/" + newName);
				itemCommand.getUpload().transferTo(file);
			}
		}catch(IOException e){
			e.printStackTrace();
		}catch(Exception e){
			e.printStackTrace();
		}		
		
		
		return "redirect:/shop/itemList.do";
	}
	
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		binder.registerCustomEditor(Integer.class, new CustomNumberEditor(Integer.class, false));
		binder.setValidator(new ItemValidator());
	}
	
}
